import React, { Fragment } from 'react';
import { TagsOutlined } from '@ant-design/icons';
import { useEditor } from '@craftjs/core';
import styles from './index.less';

// 获取节点列表：{id: string; displayName: string; name: string;}[]
const getParentNodes = (opts, id) => {
  const result = [];
  const loop = (mappings, id) => {
    if (mappings[id]) {
      result.unshift({
        id,
        name: mappings[id].data?.name,
        displayName: mappings[id].data?.displayName,
      });
      loop(mappings, mappings[id].data?.parent);
    }
  };
  loop(opts, id);
  return result;
};

export default () => {
  const {
    actions: { selectNode },
    selected,
  } = useEditor((state, query) => {
    const currentSelectedId = query.getEvent('selected').last();
    let selected;
    if (currentSelectedId) {
      selected = {
        id: currentSelectedId, // 当前节点Id
        nodeList: getParentNodes(state.nodes, currentSelectedId), // 根据选中节点获取父节点列表
        settings:
          state.nodes[currentSelectedId].related && state.nodes[currentSelectedId].related.settings, // 组件属性控制模块
      };
    }
    return { selected };
  });

  return (
    <div className={styles.rightAttributeContainer}>
      {selected ? (
        <div className={styles.rightAttributeContent}>
          {/* 组件路径 */}
          <div className={styles.rightAttributeBreadcrumb}>
            <div className={styles.rightAttributeBreadcrumbIcon}>
              <TagsOutlined />
            </div>
            <div className={styles.rightAttributeBreadcrumbList}>
              <div className={styles.rightAttributeBreadcrumbListContent}>
                {selected.nodeList.map(({ id, displayName }, index) => (
                  <Fragment key={id}>
                    {!!index && <span className={styles.rightAttributeBreadcrumbItemSplit}>/</span>}
                    <span
                      onClick={() => {
                        if (index !== selected.nodeList.length - 1) {
                          selectNode(id);
                        }
                      }}
                    >
                      {displayName}
                    </span>
                  </Fragment>
                ))}
              </div>
            </div>
          </div>
          {/* 组件设置 */}
          <div className={styles.rightAttributeSettings}>
            {selected.settings && React.createElement(selected.settings)}
          </div>
        </div>
      ) : (
        <span className={styles.rightAttributeContainerEmpty}>请在左侧画布选中节点</span>
      )}
    </div>
  );
};
